import router from './router'
import store from './store'
import NProgress from 'nprogress'
import config from './config' // 路由白名单路径集
import { GENERATE_ROUTES } from '@/store/modules/permission'
import 'nprogress/nprogress.css' // nprogress 进度条
const { isOpenAsyncRoutes, routerWhiteLists, isNprogress } = config// 进度条样式
NProgress.configure({
  showSpinner: false
}) // 不显示转圈
// 是否加载过动态路由
let isGetAsyncRoutes = false
router.beforeEach((to, from, next) => {
  if (isNprogress) NProgress.start()

  // 是否存在token 登入
  if (store.state.user.userInfo.accessToken) {
    if (to.path === '/page/login') {
      next('/')
    } else {
      if (isOpenAsyncRoutes && isGetAsyncRoutes) next()
      if (!store.state.permission.addRouters.length && isOpenAsyncRoutes) {
        // 动态路由添加
        setTimeout(() => {
          store.dispatch(GENERATE_ROUTES, ['admin.item']).then((res) => {
            router.addRoutes(res)
            isGetAsyncRoutes = true
            next()
          })
        }, 200)
        next()
      } else {
        next()
      }
    }
  } else {
    if (to.path === '/page/login') {
      next()
    } else {
      if (routerWhiteLists.indexOf(to.path) >= 0) {
        next()
      } else {
        next({
          path: `/page/login?redirect=${to.path}`
        })
      }
    }
  }
})
router.afterEach(() => {
  if (isNprogress) NProgress.done()
})
